package boundarys;

import java.awt.EventQueue;
import java.awt.List;

import javax.swing.JFrame;
import javax.swing.JButton;

import controllers.WeeklyAnalysisController;

import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.swing.JList;

import entitys.Customer;
import entitys.Reply;
import entitys.Request;
import enums.Command;

public class WeeklyAnalysisGUI extends AbstractGUI {

	private JFrame frmCcrmWA;
	List list=null;
	JButton btnExport=null;
	public WeeklyAnalysisGUI() {
		initialize();
		initGUI(frmCcrmWA);
		
		JButton btnAnalyze = new JButton("Analyze");
		btnAnalyze.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				WeeklyAnalysisController.getWeeklyAnalysis();
			}
		});
		frmCcrmWA.getContentPane().add(btnAnalyze, BorderLayout.SOUTH);
		
		list = new List();
		list.setEnabled(false);
		frmCcrmWA.getContentPane().add(list, BorderLayout.CENTER);
		
		btnExport = new JButton("Export");
		btnExport.setEnabled(false);
		btnExport.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				PrintWriter pw = null;
				try {
					pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("Weekly Analysis.txt"), "UTF-8"));
				} catch (UnsupportedEncodingException | FileNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			    try {
			        int len = list.getItemCount();
			        for (int i = 0; i < len; i++) {
			            pw.println(list.getItem(i).toString());
			        }
			    } finally {
			        pw.close();
			    }
			}
		});
		frmCcrmWA.getContentPane().add(btnExport, BorderLayout.NORTH);
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmCcrmWA = new JFrame();
		frmCcrmWA.setTitle("CCRM>Weekly Analysis");
		frmCcrmWA.setResizable(false);
		frmCcrmWA.setBounds(100, 100, 450, 300);
		frmCcrmWA.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frmCcrmWA.setVisible(true);
	}

	@Override
	public void getReply(Object r) {
		if(((Reply)r).command.equals(Command.WEEKLY_ANALSYS))
		{
			list.removeAll();
			ArrayList<Customer> cust= (ArrayList<Customer>) ((Reply)r).result;
			for(Customer c:cust)
			{
				list.add(c.toStringSeg());
			}
			btnExport.setEnabled(true);
		}
		
	}

}
